// pages/blueconn/blueconn.js
var app = getApp()
var url = require("./../../utils/index.js")
var esc = require("../../../utils/esc.js");
var play = require("../../../utils/play.js")
var timer = null
var isAuto = true
var encode = require("../../../utils/encoding.js");
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentDeviceId: '',
    list: [],
    services: [],
    serviceId: 0,
    writeCharacter: false,
    readCharacter: false,
    notifyCharacter: false,
    isScanning: false,
    looptime: 0,
    currentTime: 1,
    lastData: 0,
    oneTimeData: 0,
    buffSize: [],
    buffIndex: 0, //发送字节数下标
    printNum: [],
    printNumIndex: 0,
    printerNum: 1,
    currentPrint: 1,
    isReceiptSend: false,
    isQuery: false,
    imageSrc: '../../imags/wechat.png',
    jpgSrc: '../../imags/flower2.jpg',
    canvasWidth: 100,
    canvasHeight: 100,
    jpgWidth: 200,
    jpgHeight: 200,
    result: 0,
  },
  //搜索设备
  startSearch: function () {
    var that = this
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.getBluetoothAdapterState({
          success: function (res) {
            console.log('openBluetoothAdapter success', res)
            if (res.available) {
              if (res.discovering) {
                wx.stopBluetoothDevicesDiscovery({
                  success: function (res) {
                    console.log(res)
                  }
                })
              } else {
                // that.startBluetoothDevicesDiscovery()
                that.getBluetoothDevices()
              }
              // that.checkPemission()
            } else {
              wx.showModal({
                title: '提示',
                content: '本机蓝牙不可用',
                showCancel: false
              })
            }
          },
        })
      }, fail: function (fail) {
        console.log(fail)
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }

        wx.showModal({
          title: '提示',
          content: '蓝牙初始化失败，请到设置打开蓝牙',
          showCancel: false
        })
      }
    })
  },
  checkPemission: function () {  //android 6.0以上需授权地理位置权限
    var that = this
    if (wx.getStorageSync('platform') == "ios") {
      // app.globalData.platform = "ios"
      that.getBluetoothDevices()
    } else if (wx.getStorageSync('platform') == "android") {
      // app.globalData.platform = "android"
      console.log(app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1))
      if (app.getSystem().substring(app.getSystem().length - (app.getSystem().length - 8), app.getSystem().length - (app.getSystem().length - 8) + 1) > 5) {
        wx.getSetting({
          success: function (res) {
            console.log(res)
            if (!res.authSetting['scope.userLocation']) {
              wx.authorize({
                scope: 'scope.userLocation',
                complete: function (res) {
                  that.getBluetoothDevices()
                }
              })
            } else {
              that.getBluetoothDevices()
            }
          }
        })
      }
    }
  },
  getBluetoothDevices: function () {  //获取蓝牙设备信息
    var that = this
    console.log("start search")
    wx.showLoading({
      title: '正在加载',
      icon: 'loading',
    })
    that.setData({
      isScanning: true
    })
    wx.startBluetoothDevicesDiscovery({
      success: function (res) {
        console.log(res)
        setTimeout(function () {
          wx.getBluetoothDevices({
            success: function (res) {
              console.log(res.devices)
              var devices = []
              var num = 0
              for (var i = 0; i < res.devices.length; ++i) {
                if (res.devices[i].name != "未知设备" && res.devices[i].advertisServiceUUIDs.length > 0) {
                  devices[num] = res.devices[i]
                  num++
                }
              }
              that.setData({
                list: devices,
                isScanning: false
              })
              console.log(devices)
              wx.hideLoading()
              wx.stopPullDownRefresh()
              wx.stopBluetoothDevicesDiscovery({
                success: function (res) {
                  console.log("停止搜索蓝牙")
                }
              })
            },
          })
        }, 5000)
      },
    })
  },
  unConnect: function () {
    var that = this
    console.log('断开蓝牙：' + wx.getStorageSync('deviceId'))
    wx.closeBLEConnection({
      deviceId: wx.getStorageSync('deviceId'),
      success(res) {
        console.log('断开蓝牙连接')
        that.setData({
          currentDeviceId: ''
        })
        isAuto = false
        wx.removeStorageSync('deviceId')
        clearInterval(timer)
      }
    })
  },
  bindViewTap: function (e) {
    var that = this
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) { console.log(res) },
    })
    that.setData({
      serviceId: 0,
      writeCharacter: false,
      readCharacter: false,
      notifyCharacter: false
    })
    console.log(e.currentTarget.dataset.title)
    wx.showLoading({
      title: '正在连接',
    })
    wx.createBLEConnection({
      deviceId: e.currentTarget.dataset.title,
      success: function (res) {
        console.log(res)
        // app.BLEInformation.deviceId = e.currentTarget.dataset.title
        wx.setStorageSync('deviceId', e.currentTarget.dataset.title)
        that.setData({
          currentDeviceId: e.currentTarget.dataset.title
        })
        isAuto = true
        clearInterval(timer)
        console.log('清空定时器1' + timer)
        that.getSeviceId()
      }, fail: function (e) {
        wx.showModal({
          title: '提示',
          content: '连接失败',
          showCancel: false
        })
        console.log(e)
        wx.hideLoading()
      }, complete: function (e) {
        console.log(e)
      }
    })

    wx.onBLEConnectionStateChange(function (res) {
      // 该方法回调中可以用于处理连接意外断开等异常情况
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
      if (res.connected == false && isAuto == true) {
        timer = setInterval(() => {
          wx.createBLEConnection({
            deviceId: res.deviceId,
            success: function (res) {
              console.log('蓝牙连接成功：' + JSON.stringify(res))
              that.getSeviceId()
              // app.BLEInformation.deviceId = e.currentTarget.dataset.title
            },
            // fail: function (e) {
            //   wx.showModal({
            //     title: '提示',
            //     content: '连接失败',
            //     showCancel: false
            //   })
            //   console.log(e)
            //   wx.hideLoading()
            // }, complete: function (e) {
            //   console.log(e)
            // }
          })
        }, 1000)
      }
      if (res.connected == true) {
        wx.setStorageSync('deviceId', res.deviceId)
        console.log(wx.getStorageSync('deviceId'))
        that.setData({
          currentDeviceId: res.deviceId
        })
        clearInterval(timer)
        console.log('清空定时器2' + timer)
      }
    })
  },
  getSeviceId: function () {
    var that = this
    var platform = wx.getStorageSync('platform')
    wx.getBLEDeviceServices({
      deviceId: wx.getStorageSync('deviceId'),
      success: function (res) {
        console.log(res)
        // var realId = ''
        // if (platform == 'android') {
        //   // for(var i=0;i<res.services.length;++i){
        //   // var item = res.services[i].uuid
        //   // if (item == "0000FEE7-0000-1000-8000-00805F9B34FB"){
        //   realId = "0000FEE7-0000-1000-8000-00805F9B34FB"
        //   //       break;
        //   //     }
        //   // }
        // } else if (platform == 'ios') {
        //   // for(var i=0;i<res.services.length;++i){
        //   // var item = res.services[i].uuid
        //   // if (item == "49535343-FE7D-4AE5-8FA9-9FAFD205E455"){
        //   realId = "49535343-FE7D-4AE5-8FA9-9FAFD205E455"
        //   // break
        //   // }
        //   // }
        // }
        // app.BLEInformation.serviceId = realId
        that.setData({
          services: res.services
        })
        that.getCharacteristics()
      }, fail: function (e) {
        console.log(e)
      }, complete: function (e) {
        console.log(e)
      }
    })
  },
  getCharacteristics: function () {
    var that = this
    var list = that.data.services
    var num = that.data.serviceId
    var write = that.data.writeCharacter
    var read = that.data.readCharacter
    var notify = that.data.notifyCharacter
    wx.getBLEDeviceCharacteristics({
      deviceId: wx.getStorageSync('deviceId'),
      serviceId: list[num].uuid,
      success: function (res) {
        console.log(res)
        for (var i = 0; i < res.characteristics.length; ++i) {
          var properties = res.characteristics[i].properties
          var item = res.characteristics[i].uuid
          if (!notify) {
            if (properties.notify) {
              wx.setStorageSync('notifyCharaterId', item)
              wx.setStorageSync('notifyServiceId', list[num].uuid)
              // app.BLEInformation.notifyCharaterId = item
              // app.BLEInformation.notifyServiceId = list[num].uuid
              notify = true
            }
          }
          if (!write) {
            if (properties.write) {
              wx.setStorageSync('writeCharaterId', item)
              wx.setStorageSync('writeServiceId', list[num].uuid)
              // app.BLEInformation.writeCharaterId = item
              // app.BLEInformation.writeServiceId = list[num].uuid
              write = true
            }
          }
          if (!read) {
            if (properties.read) {
              wx.setStorageSync('readCharaterId', item)
              wx.setStorageSync('readServiceId', list[num].uuid)
              // app.BLEInformation.readCharaterId = item
              // app.BLEInformation.readServiceId = list[num].uuid
              read = true
            }
          }
        }
        if (!write || !notify || !read) {
          num++
          that.setData({
            writeCharacter: write,
            readCharacter: read,
            notifyCharacter: notify,
            serviceId: num
          })
          if (num == list.length) {
            wx.showModal({
              title: '提示',
              content: '找不到该读写的特征值',
              showCancel: false
            })
          } else {
            that.getCharacteristics()
          }
        } else {
          wx.showToast({
            title: '连接成功',
          })
          that.openControl()
        }
      }, fail: function (e) {
        console.log(e)
      }, complete: function (e) {
        // console.log("write:" + app.BLEInformation.writeCharaterId)
        // console.log("read:" + app.BLEInformation.readCharaterId)
        // console.log("notify:" + app.BLEInformation.notifyCharaterId)
      }
    })
  },
  openControl: function () {//连接成功
    this.onWebsocket()
    wx.reLaunch({
      url: '/pages/mypage/index'
    })
  },
  receiptTest: function (text) { //票据测试
    var that = this;
    var canvasWidth = that.data.canvasWidth
    var canvasHeight = that.data.canvasHeight
    var command = esc.jpPrinter.createNew()
    var y = 1
    command.init() //初始化打印机
    command.setSelectJustification(1) //居中
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText(text.storeName);
    command.setPrint(); //打印并换行

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    command.setSelectJustification(1) //居中
    command.setCharacterSize(22); //设置倍高倍宽
    command.setText('--已在线支付--');
    command.setPrint(); //打印并换行
    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    if (text.tableNo) {
      command.setSelectJustification(1)
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText('餐桌号：' + text.tableNo);
      command.setPrint()
    } else {
      command.setSelectJustification(1)
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText('出餐号：' + text.orderNo.substr(-3));
      command.setPrint()
    }

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('----------------');
    command.setPrint()

    command.setSelectJustification(0) //设置居左
    command.setCharacterSize(0); //设置倍高倍宽
    command.setText("下单时间：" + text.createTime)
    command.setPrint() //打印并换行

    command.setSelectJustification(0) //设置居左
    command.setText("订单编号：" + text.orderNo)
    command.setPrint() //打印并换行

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    command.setSelectJustification(1) //居中
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText('--1号篮子--');
    command.setPrint(); //打印并换行

    var list = text.list
    command.setCharacterSize(0); //设置倍高倍宽
    for (var i = 0; i < list.length; i++) {
      command.setSelectJustification(0)
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText('');
      command.setPrint()

      command.setSelectJustification(0)
      command.setText(list[i].prodName);
      command.setAbsolutePrintPosition(268)
      command.setText('x' + list[i].num);
      command.setAbsolutePrintPosition(336)
      command.setText(list[i].price);
      command.setPrint()

      command.setSelectJustification(0)
      command.setCharacterSize(10); //设置倍高倍宽
      command.setAbsolutePrintPosition(100)
      command.setText('规格' + list[i].specName.split('规格')[1]);

      command.setSelectJustification(0)
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText('');
      command.setPrint()
    }

    command.setSelectJustification(1) //居中
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText('--其他费用--');
    command.setPrint(); //打印并换行

    command.setSelectJustification(0)
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    // command.setSelectJustification(0)
    // command.setCharacterSize(0); //设置倍高倍宽
    // command.setText("红包：");
    // command.setAbsolutePrintPosition(306)
    // command.setText(text.lessPrice);
    // command.setPrint()

    command.setSelectJustification(0)
    command.setText("配送费：");
    command.setAbsolutePrintPosition(286)
    command.setText(text.delFee ? text.delFee : 0);
    command.setPrint()

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('----------------');
    command.setPrint()

    // command.setSelectJustification(0)
    // command.setCharacterSize(0); //设置倍高倍宽
    // command.setText("原价：");
    // command.setAbsolutePrintPosition(326)
    // command.setText('￥' + text);
    // command.setPrint()

    command.setSelectJustification(0)
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText("实付：");
    command.setAbsolutePrintPosition(286)
    command.setText('￥' + text.price);
    command.setPrint()

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('----------------');
    command.setPrint()

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    if (text.datVipAddress) {
      command.setSelectJustification(0) //设置居左
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText(text.datVipAddress.name)
      command.setPrint() //打印并换行

      command.setSelectJustification(0)
      command.setCharacterSize(17); //设置倍高倍宽
      command.setText('');
      command.setPrint()

      command.setSelectJustification(0) //设置居左
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText(text.datVipAddress.phone)
      command.setPrint() //打印并换行

      command.setSelectJustification(0)
      command.setCharacterSize(17); //设置倍高倍宽
      command.setText('');
      command.setPrint()

      command.setSelectJustification(0) //设置居左
      command.setCharacterSize(12); //设置倍高倍宽
      command.setText("地址：" + text.datVipAddress.address + text.datVipAddress.detAddress)
      command.setPrint() //打印并换行

      command.setSelectJustification(0)
      command.setCharacterSize(17); //设置倍高倍宽
      command.setText('');
      command.setPrint()
    }

    command.setSelectJustification(0) //设置居左
    command.setCharacterSize(12); //设置倍高倍宽
    command.setText("备注：" + text.orderRemark)
    command.setPrint() //打印并换行


    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    command.setSelectJustification(1) //居中
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('--已完结--')
    command.setPrint() //打印并换行

    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()
    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()
    command.setSelectJustification(0)
    command.setCharacterSize(17); //设置倍高倍宽
    command.setText('');
    command.setPrint()

    // that.queryStatus()
    that.prepareSend(command.getData())//准备发送数据
  },
  prepareSend: function (buff) { //准备发送，根据每次发送字节数来处理分包数量
    console.log('接收到数据：' + buff)
    var that = this
    var time = that.data.oneTimeData
    var looptime = parseInt(buff.length / time);
    var lastData = parseInt(buff.length % time);
    console.log("prepareSend")
    console.log(looptime + "---" + lastData)
    that.setData({
      looptime: looptime + 1,
      lastData: lastData,
      currentTime: 1,
    })
    that.Send(buff)
    // if (that.result == 12) {
    //   that.Send(buff)
    // }
  },
  Send: function (buff) { //分包发送
    var that = this
    var currentTime = that.data.currentTime
    var loopTime = that.data.looptime
    var lastData = that.data.lastData
    var onTimeData = that.data.oneTimeData
    var printNum = that.data.printerNum
    var currentPrint = that.data.currentPrint
    var buf
    var dataView
    console.log("buff")
    console.log(buff)
    if (currentTime < loopTime) {
      buf = new ArrayBuffer(onTimeData)
      dataView = new DataView(buf)
      for (var i = 0; i < onTimeData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    } else {
      buf = new ArrayBuffer(lastData)
      dataView = new DataView(buf)
      for (var i = 0; i < lastData; ++i) {
        dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
      }
    }
    //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
    wx.writeBLECharacteristicValue({
      deviceId: wx.getStorageSync('deviceId'),
      serviceId: wx.getStorageSync('writeServiceId'),
      characteristicId: wx.getStorageSync('writeCharaterId'),
      value: buf,
      success: function (res) {
        if (currentTime <= loopTime) {
          // wx.showLoading({
          //   title: '传输中...',
          // })
        } else {
          wx.showToast({
            title: '已打印第' + currentPrint + '张成功',
          })
        }
        //console.log(res)
      },
      fail: function (e) {
        wx.showToast({
          title: '打印第' + currentPrint + '张失败',
          icon: 'none',
        })
        console.log(wx.getStorageSync('deviceId'))
        console.log(wx.getStorageSync('writeServiceId'))
        console.log(wx.getStorageSync('writeCharaterId'))
        console.log('打印第' + currentPrint + '张失败')
        console.log(e)
      },
      complete: function () {
        currentTime++
        play.soptAudio()
        if (currentTime <= loopTime) {
          that.setData({
            currentTime: currentTime
          })
          that.Send(buff)
        } else {
          if (currentPrint == printNum) {
            that.setData({
              looptime: 0,
              lastData: 0,
              currentTime: 1,
              isReceiptSend: false,
              currentPrint: 1
            })
          } else {
            currentPrint++
            that.setData({
              currentPrint: currentPrint,
              currentTime: 1,
            })
            that.Send(buff)
          }
        }
      }
    })
  },
  queryStatus: function () { //查询打印机状态
    var that = this
    var buf;
    var dateView;
    /*
    n = 1：传送打印机状态
    n = 2：传送脱机状态
    n = 3：传送错误状态
    n = 4：传送纸传感器状态
    */
    buf = new ArrayBuffer(3)
    dateView = new DataView(buf)
    dateView.setUint8(0, 16)
    dateView.setUint8(1, 4)
    dateView.setUint8(2, 2)
    wx.writeBLECharacteristicValue({
      deviceId: wx.getStorageSync('deviceId'),
      serviceId: wx.getStorageSync('writeServiceId'),
      characteristicId: wx.getStorageSync('writeCharaterId'),
      value: buf,
      success: function (res) {
        console.log("发送成功")
        that.setData({
          isQuery: true
        })
      },
      fail: function (e) {
        wx.showToast({
          title: '发送失败',
          icon: 'none',
        })
        //console.log(e)
        return;
      },
      complete: function () {

      }
    })
    wx.notifyBLECharacteristicValueChange({
      deviceId: wx.getStorageSync('deviceId'),
      serviceId: wx.getStorageSync('notifyServiceId'),
      characteristicId: wx.getStorageSync('notifyCharaterId'),
      success: function (res) {
        wx.onBLECharacteristicValueChange(function (r) {
          console.log(`characteristic ${r.characteristicId} has changed, now is ${r}`)
          var result = ab2hex(r.value)
          console.log("返回" + result)
          var tip = ''
          if (result == 12) { //正常
            tip = "正常"
          } else if (result == 32) { //缺纸
            tip = "缺纸"
          } else if (result == 36) { //开盖、缺纸
            tip = "开盖、缺纸"
          } else if (result == 16) {
            tip = "开盖"
          } else if (result == 40) { //其他错误
            tip = "其他错误"
          } else { //未处理错误
            tip = "未知错误"
          }
          that.setData({
            result: result,
          })
          if (result == 32 || result == 36 || result == 16 || result == 40) {
            wx.showModal({
              title: '打印机状态',
              content: tip,
              showCancel: false
            })
          }
        })
      },
      fail: function (e) {
        wx.showModal({
          title: '打印机状态',
          content: '获取失败',
          showCancel: false
        })
      },
      complete: function (e) {
        that.setData({
          isQuery: false
        })
        console.log("执行完成")
      }
    })
  },
  onWebsocket: function () {
    var user = wx.getStorageSync('user')
    var that = this
    // 1. 创建WebSocket连接
    if (user.openId) {
      wx.connectSocket({
        url: url.WebSocketUrl + '/api/anon/ws/payOrder/' + user.openId + '/' + new Date().getTime()
      })
      // 2. 监听WebSocket连接状态
      wx.onSocketOpen(function () {
        console.log('WebSocket连接已打开')
      })
      wx.onSocketError(function (res) {
        console.log('WebSocket连接打开失败:', res)
        // that.onWebsocket()
      })
      wx.onSocketClose(function () {
        console.log('WebSocket连接已关闭')
        that.onWebsocket()
        wx.showToast({
          title: 'WebSocket连接已关闭',
          icon: 'error',
          duration: 2000
        })
      })
      // 3. 发送和接收数据
      wx.sendSocketMessage({
        data: 'Hello, WebSocket!'
      })
      wx.onSocketMessage(function (res) {
        var list = JSON.parse(res.data).did
        that.receiptT(list)
        // for (var i = 0; i < list.length; i++) {
        //   wx.request({
        //     url: 'https://cxj.szzkba.cn/prod-api/pet/order/getOrderInfoByPay/' + list[i], //仅为示例，并非真实的接口地址
        //     // url: 'https://cxjadmin.szzkba.cn/prod-api/pet/order/getOrderInfoByPay/' + list[i], //仅为示例，并非真实的接口地址
        //     header: {
        //       'content-type': 'application/json', // 默认值
        //       'Authorization': 'Bearer ' + wx.getStorageSync('token')
        //     },
        //     success(res) {
        //       if (res.data.code == 200) {
        //         var list = res.data.data
        //         that.receiptTest(list[0])
        //         // that.receiptTest(list[0])
        //         // setTimeout(function () {
        //         //   console.log("延时10秒后执行");
        //         //   that.receiptTest(list[0])
        //         // }, 10000 * (i));
        //       }
        //     }
        //   })
        // }
      })
    }
    // 4. 关闭WebSocket连接
    // wx.closeSocket()
  },
  requestT: function (val) {
    // var tempURL = 'https://cxj.szzkba.cn/prod-api/pet/order/getOrderInfoByPay/' + val
    var tempURL = 'https://cxjadmin.szzkba.cn/prod-api/pet/order/getOrderInfoByPay/' + val
    return new Promise(function (resolve, reject) {
      wx.request({
        url: tempURL,
        header: {
          'content-type': 'application/json', // 默认值
          'Authorization': 'Bearer ' + wx.getStorageSync('token')
        },
        success: function (res) {
          resolve(res.data); // 请求成功，调用resolve方法
        },
        fail: function (err) {
          reject(err); // 请求失败，调用reject方法
        }
      });
    })
  },
  async receiptT(list) {
    var that = this
    var tempList = []
    for (var i = 0; i < list.length; i++) {
      var res = await that.requestT(list[i])
      tempList.push(res.data[0])
      console.log(res.data)
    }
    var j = 0
    for (var i = 0; i < tempList.length; i++) {
      play.playAudio()
      if (i == 0) {
        that.receiptTest(tempList[i])
        j++
      } else {
        setTimeout(function () {
          that.receiptTest(tempList[j])
          j++
        }, 8000 * (i));
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // app.BLEInformation.platform = app.getPlatform()
    // console.log(app.getPlatform())
    // wx.setStorage({
    //   key: "platform",
    //   data: app.getPlatform()
    // })
    this.setData({
      currentDeviceId: wx.getStorageSync('deviceId')
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var list = []
    var numList = []
    var j = 0
    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++
    }
    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i
    }
    this.setData({
      buffSize: list,
      oneTimeData: list[0],
      printNum: numList,
      printerNum: numList[0]
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  // /**
  //  * 页面相关事件处理函数--监听用户下拉动作
  //  */
  // onPullDownRefresh: function () {
  //     // var that = this
  //     // wx.startPullDownRefresh({})
  //     // that.startSearch()
  // },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})